package com.software.avatar.activity;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.ImageDecoder;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.software.avatar.R;
import com.software.avatar.utils.HostUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HomePageActivity extends AppCompatActivity {

    private TextView tv_mine_phone;
    private TextView tv_mine_password;
    private ImageView iv_avatar;
    private ActivityResultLauncher launcher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_page);
        initViews();
        initData();
        initEvents();
        initLauncher();
    }

    private void initLauncher() {
        launcher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == RESULT_OK) {
                            Uri uri = result.getData().getData();
                            ImageDecoder.Source source = ImageDecoder.createSource(getContentResolver(), uri);
                            try {
                                Bitmap bitmap = ImageDecoder.decodeBitmap(source);
                                iv_avatar.setImageBitmap(bitmap);
                                //上传头像
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        uploadAvatar(uri);
                                    }
                                });
                                
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
        );
    }

    private void uploadAvatar(Uri uri) {
        String path = String.format(
                HostUtil.HOST + "/upload?phone=%s",
                tv_mine_phone.getText().toString()
        );
        InputStream is = null;
        OutputStream os = null;
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            is = getContentResolver().openInputStream(uri);
            os = conn.getOutputStream();
            //边读边写
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
                os.flush();

            }
            //获取服务端响应回来的信息
            if (conn.getResponseCode() == 200) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(HomePageActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
                    }
                });

            }else {
                String responseMessage = conn.getResponseMessage();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(HomePageActivity.this, responseMessage, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }

    private void initEvents() {
        iv_avatar.setOnClickListener(v -> {
            Intent intent = new Intent(
                    Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            );
            launcher.launch(intent);

        });

    }

    private void initData() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        String phone = bundle.getString("phone");
        String password = bundle.getString("password");
        String avatar = bundle.getString("avatar");
        tv_mine_phone.setText(phone);
        tv_mine_password.setText(password);

    }

    private void initViews() {
        iv_avatar = findViewById(R.id.iv_avatar);
        tv_mine_password = findViewById(R.id.tv_mine_password);
        tv_mine_phone = findViewById(R.id.tv_mine_phone);
    }
}